import { defineStore } from 'pinia'
import {
  updateGoodsCountApi,
  getShoppingCartItemCountApi,
  getShoppingCartItemListApi,
  deleteShoppingCartItemApi

} from '@/apis/shopping'
import { ref, computed } from 'vue'


// 维护购物车中商品数量的状态
export const useCartStore = defineStore('cart', () => {
  const count = ref(0)
  const cartList = ref([])
  const selectAll = ref(true)


  const totalPrice = computed(() => cartList.value.reduce((acc, item) =>
    acc + (item.checked ? item.sellingPrice * item.goodsCount : 0), 0).toFixed(2))

  // 获取购物车中商品数量 , 一旦出现修改购物车数据，就调用该函数
  const getCount = async (flag = true) => {
    const token = await uni.getStorage({
      key: 'token'
    })
	// 修改购物车数量
    if (token) {
      const res = await getShoppingCartItemCountApi()
      count.value = res.data.data
      if (flag) {
        uni.setTabBarBadge({
          index: 2,
          text: count.value + ''
        })
      }
    }
  }
	// 获取购物车列表
  const getCartList = async () => {
    const res = await getShoppingCartItemListApi()
    cartList.value = res.data.data
    cartList.value = cartList.value.map(item => {
      return {
        ...item,
        checked: true
      }
    })

  }

  // 将全选的设置每一个商品
  const selectAllChange = (e) => {
    selectAll.value = e
    cartList.value.filter(item => item.checked = selectAll.value)
  }

  // 单选
  const checkBoxChange = (id) => {
    cartList.value.filter(item => {
      if (item.id === id) {
        item.checked = !item.checked
      }
    })

    selectAll.value = cartList.value.every(item => item.checked)

  }

  // 修改数量
  const numberChange = async (number, index) => {
    const item = cartList.value[index]
    await updateGoodsCountApi({
      id: item.id,
      goodsId: item.goodsId,
      goodsCount: number,
    })
    item.goodsCount = number
    getCount(true)
  }

  // 删除
  const deleteItem = async (id, index) => {
    await deleteShoppingCartItemApi(id)
    cartList.value.splice(index, 1)
    getCount(true)
  }

  return {
    count,
    getCount,
    cartList,
    getCartList,
    totalPrice,
    selectAllChange,
    selectAll,
    checkBoxChange,
    numberChange,
    deleteItem
  }
})